package com.mccken.practice.top100.Top_30$.Top_33;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: mccken-collect
 * @description:
 * @author: mccken
 * @create: 2024-02-28 22:39
 **/
public class LRUCache {

	private final static Integer NON_NODE = -1;
	
	/**
	 * 设计一个数据结构
	 * 底层是一个双链表和hash表
	 */
	static class DLinkedNode {
		int key;
		int value;
		DLinkedNode prev;
		DLinkedNode next;
		public DLinkedNode() {
			
		}
		
		public DLinkedNode(int key, int value){
			this.key = key;
			this.value = value;
		}
	}
	
	private Map<Integer, DLinkedNode> cache = new HashMap<>();
	private int size;
	// capacity >= 1
	private int capacity;
	private DLinkedNode head, tail;


	public LRUCache(int capacity) {
		this.size = 0;
		this.capacity = capacity;
		head = new DLinkedNode(-2, 0);
		tail = new DLinkedNode(-3, 0);
		head.next = tail;
		tail.prev = head;
	}

	public int get(int key) {
		DLinkedNode node = cache.get(key);
		if (node == null) {
			return NON_NODE;
		}
		
		// 将他设置为头结点
		setNew(node, true);
		return node.value;
	}

	private void setNew(DLinkedNode node, boolean inLinked) {
		DLinkedNode headNext = head.next;
		
		// 自己就是该节点了
		if (headNext == node) {
			return;
		}
		
		if (inLinked) {
			// 断开自己
			node.prev.next = node.next;
			node.next.prev = node.prev;	
		}
		
		
		// 插入到头中
		head.next = node;
		node.next = headNext;
		headNext.prev = node;
		node.prev = head;
	}
	
	public void put(int key, int value) {
		// 判断是否存在
		DLinkedNode node = cache.get(key);
		if (node != null) {
			// 修改值，并且提拔为新节点
		    node.value = value;
			setNew(node, true);	
		} else {
			if (size == capacity) {
				poll();
			}

			DLinkedNode newNode = new DLinkedNode(key, value);
			cache.put(key, newNode);
			setNew(newNode, false);

			size++;	
		}
	}
	
	private DLinkedNode poll() {
		if (size <= 0) {
			return null;
		}

		DLinkedNode del = tail.prev;
		DLinkedNode delPrev = del.prev;
		delPrev.next = tail;
		tail.prev = delPrev;
		del.prev = null;
		del.next = null;
		size--;
		
		cache.remove(del.key);
		
		return del;
	}

	public static void main(String[] args) {

		LRUCache lRUCache = new LRUCache(2);
		lRUCache.put(1, 1); // 缓存是 {1=1}
		lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
		System.out.println(lRUCache.get(1));    // 返回 1
		lRUCache.put(3, 3); // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
		System.out.println(lRUCache.get(2));    // 返回 -1 (未找到)
		lRUCache.put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
		System.out.println(lRUCache.get(1));    // 返回 -1 (未找到)
		System.out.println(lRUCache.get(3));;    // 返回 3
		System.out.println(lRUCache.get(4));;    // 返回 4
	}
}
